<template>
  <div id="uploadFiles">
    <Upload
      :action="url"
      :multiple="multiple"
      :data="extraData"
      type="drag"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :show-upload-list="false"
      ref="uploadFiles"
      :on-format-error="handleFormatError"
      name="name"
      :accept="accept"
      :format="format"
    >
      <div
        class="uploadBox"
        style="width:100%"
        :style="{'height':boxHeight+'px'}"
        v-if="fileDatas.length<=0"
      >
        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
        <p>
          请上传{{name}}文件
          <span v-if="maxSize<40960"></span>
        </p>
      </div>
      <!-- 图片 -->
      <div style="width:100%" class="fileBox" :style="{'height':boxHeight+'px'}" v-else>
        <div
          class="fileBoxOne"
          :class="fileWidth==127&&fileHeight==130?'initialClass':'changeClass'"

          @click.stop
          v-for="(item,index) in fileDatas"
          :key="index"
        >
          <div
            class="fileBoxImg"
            v-if="item.src&&(item.src.indexOf('blob')===0||item.src.indexOf('jpg')===item.src.length-3||item.src.indexOf('png')===item.src.length-3)"
          >
            <img
              :src="getImgSrc(item)"
              :onerror="defaultImg"
            >
            <div class="fileBoxOneName">
              <p v-if="item.name.length<8">{{item.name}}</p>
              <p
                v-else
                :title="item.name"
              >{{item.name.substring(0,8)+'...'+item.name.split('.')[item.name.split('.').length-1]}}</p>
            </div>
            <div class="fileBoxOneClose" @click="delImg($event,index)">
              <Icon type="close-round" color="red" size="18"/>
            </div>
          </div>
          <div class="fileBoxFiles" v-else>
            <img
              :src="getImgSrc(item)+'?r='+Math.random()"
              alt
              :style="{width:fileWidth - 61 + 'px',height:fileHeight - 64 + 'px'}"
            >
            <Tooltip :content="item.name" placement="top" transfer style="display:block">
              <p v-if="item.name.length<5">{{item.name}}</p>
              <p
                v-else
              >{{item.name.substring(0,5)+'...'+item.name.split('.')[item.name.split('.').length-1]}}</p>
            </Tooltip>
            <div class="fileBoxOneClose" @click="delImg($event,index)">
              <Icon type="close-round" color="red" size="18"/>
            </div>
          </div>
        </div>
      </div>
    </Upload>
  </div>
</template>
<script>
export default {
  data() {
    return {
      fileDatas: [],
      defaultImg: 'this.src="' + require("./img/errorImg.png") + '"',
      allFileFormats: [],
      ultimatelyMax: "" //上传文件的格式大小
    };
  },
  props: {
    name: {
      type: String,
      default: ""
    },
    url: {
      type: String,
      default: ""
    }, //路径
    multiple: {
      type: Boolean,
      default: false
    }, //是否多选
    accept: {
      type: String,
      default:
        ".docx,.pptx,.doc,.ppt,.png,.mp4,.jpg,.gif,.xls,.xlsx,.pdf,.OTHER,.bmp"
    }, //接受上传的文件类型 string
    format: {
      type: Array,
      default: () => [
        "docx",
        "pptx",
        "doc",
        "ppt",
        "png",
        "mp4",
        "jpg",
        "gif",
        "xls",
        "xlsx",
        "pdf",
        "OTHER",
        "bmp"
      ]
    },
    extraData: {
      type: Object,
      default: () => {}
    }, //额外参数
    //编辑时的数据
    editData: {
      type: Object,
      default: () => {}
    },
    maxSize: {
      type: Number,
      default: 1000000
    },
    //最外层Box的高度
    boxHeight: {
      type: Number,
      default: 200
    },
    //每个FilesBox的宽高
    fileWidth: {
      type: Number,
      default: 127
    },
    fileHeight: {
      type: Number,
      default: 130
    },
    formatArr: {
      type: Array,
      default: () => [1, 2, 3, 4, 5]
    }
  },
  watch: {
    //当编辑数据有时push到里面显示内容
    editData: {
      immediate: true, // 很重要！！
      handler(val) {
        if (
          val.src == "" ||
          val.src == undefined ||
          val.src.indexOf("undefined") >= 0
        ) {
          return;
        } else {
          if (val.src.indexOf("http") == -1) {
            val.src = ajaxUrl + val.src
          }
        }
        if (this.multiple) {
          this.fileDatas = [];
          this.fileDatas.push(val);
        } else {
          this.fileDatas = [];
          this.fileDatas.push(val);
        }
        ////console.log(this.fileDatas);
      }
    },
    formatArr: {
      immediate: true, // 很重要！！
      deep:true,
      handler(val, oldVal) {
        if (JSON.stringify(val) != JSON.stringify(oldVal)) {
          // this.askFormat(val);
        }
      }
    }
  },
  methods: {
    getImgSrc(item) {
      console.log(item);
      try {
        if (item.name !== undefined) {
          //图片直接显示
          if (
            item.src !== undefined &&
            (item.src.indexOf("blob") !== -1 ||
              item.src.indexOf("Navigation") !== -1)
          ) {
            return item.src;
          } else {
            //判断文件格式
            var name =
              item.src && item.src.indexOf(".") !== -1 ? item.src : item.name;
            var suffix = name.split(".")[name.split(".").length - 1];
            if (suffix === "png" || suffix === "jpg" || suffix === "gif") {
              return item.src;
            } else {
              return require("./img/index/" + suffix + ".png");
            }
          }
        }
      } catch (e) {
        //未知文件
        return require("./img/file.png");
      }
    },
    getFileType(filePath) {
      var startIndex = filePath.lastIndexOf(".");
      if (startIndex != -1)
        return filePath
          .substring(startIndex + 1, filePath.length)
          .toLowerCase();
      else return "";
    },
    beforeUpload(file) {
      // if(this.format.indexOf(this.getFileType(file.name))<0){
      //    this.$Message.error(`只支持${this.accept}格式的文件`);
      //    return true;
      // }
      // if(file.size>this.maxSize*1024){
      //   this.$Message.error(`只支持上传${this.maxSize}kB以下的文件`);
      //   return true;
      // }
      if (this.multiple) {
        if (file.type.indexOf("image") > -1) {
          //证明是img文件
          var [imgSrc, imgName] = [window.URL.createObjectURL(file), file.name];
          var obj = {
            src: imgSrc,
            name: imgName
          };
          this.fileDatas.push(obj);
        } else {
          var fileObj = {
            name: file.name
          };
          this.fileDatas.push(fileObj);
        }
      } else {
        if (file.type.indexOf("image") > -1) {
          var [imgSrc, imgName] = [window.URL.createObjectURL(file), file.name];
          var obj = {
            src: imgSrc,
            name: imgName
          };
          this.fileDatas = [];
          this.fileDatas.push(obj);
        } else {
          var fileObj = {
            name: file.name
          };
          this.fileDatas = [];
          this.fileDatas.push(fileObj);
        }
      }
      this.$emit("beforeUpload", file);
      return false;
    },

    onSuccess(res) {
      this.$emit("onSuccess", res);
    },
    delImg(e, i) {
      e.stopPropagation();
      this.fileDatas.splice(i, 1);
      this.$emit("onRemove", i);
    },
    delImg1(i) {
      this.fileDatas.splice(i, 1);
    },
    clearFiles() {
      this.fileDatas = [];
    },
    //验证是否是图片格式
    valudateImgUrl(url) {
      return url.match(/\.(jpeg|jpg|gif|bmp|png)$/) != null;
    },
    //上传文件超出大小
    handleMaxSize(file) {
      this.$emit("on-exceeded-size", file);
    },
    handleFormatError(file) {
      this.$emit("on-format-error", file);
    }
  },
  mounted() {
    //得到限制的大小
    var maxSize = this.maxSize;
    //KB转换成MB
    maxSize = Number(maxSize / 1024);
    //保留两位小数
    var max = maxSize.toFixed(2);
    //以“.”截取保留的值，用于去零 如：5.00MB 则显示为5MB; 如：5.21MB 则显示为5.21MB
    var maxArray = max.split(".");
    //"."的右边的值
    var maxSplit = maxArray[1] * 1;
    //声明一个最终的值变量
    var ultimatelyMax;
    //判断右边的值是否大于等于零
    if (maxSplit <= 0) {
      //大于等于零则只显示左边的值
      ultimatelyMax = maxArray[0];
    } else {
      //否则显示全部保留两位的值
      ultimatelyMax = max;
    }
    //得到最终的值赋值给全局变量
    this.ultimatelyMax = ultimatelyMax;

    ////console.log("this.editData", this.editData);
  }
};
</script>
<style lang="less" scoped>
@import url("./upload-files");
</style>
